package com.yongqi.duocai.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.utils.ExpressInfoUtil;
import com.yongqi.duocai.entity.Order;
import com.yongqi.duocai.entity.OrderInfo;
import com.yongqi.duocai.entity.ShoppingCart;
import com.yongqi.duocai.entity.result.OrderInfoResult;
import com.yongqi.duocai.entity.result.OrderResult;
import com.yongqi.duocai.entity.result.ShoppingCarResult;
import com.yongqi.duocai.entity.vo.OrderGoodsVo;
import com.yongqi.duocai.entity.vo.OrderVo;
import com.yongqi.duocai.entity.vo.PageVo;
import com.yongqi.duocai.exception.BusinessException;
import com.yongqi.duocai.exception.ResponseEnum;
import com.yongqi.duocai.service.*;
import com.yongqi.duocai.utils.EmailUtils;
import com.yongqi.duocai.utils.JsonResult;
import com.yongqi.duocai.utils.ListUtils;
import com.yongqi.duocai.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 夏亮辉
 * @since 2021-06-24
 */
@RestController
@RequestMapping("/duocai/order")
@Api(tags = "OrderController")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private ExpressService expressService;

    @Autowired
    private ShoppingCartService shoppingCartService;


    @ApiOperation(value = "获取用户全部的订单信息")
    @GetMapping("/all")
    public JsonResult queryAll(Integer userId, Integer pageNum){
        JsonResult jsonResult = new JsonResult();
        Page page = new Page(pageNum, 4);
        IPage<OrderResult> iPage = orderService.queryPageUserId(page, userId, null);
        List<OrderResult> orders = iPage.getRecords();
        for(OrderResult o: orders){
            o.setCreateTime(o.getCreateTime().plusMinutes(30));
            String infos = o.getGoodsDetailsId();
            List<Integer> ids = StringUtils.changArr(infos);
            List<OrderGoodsVo> goodsInfo = orderInfoService.queryByIds(ids);
            o.setGoodsInfo(goodsInfo);
        }

        if(orders.size() == 0){
            jsonResult.setCode(200);
            jsonResult.setMessage("您还没有相关的订单");
        }else {
            OrderVo orderVo = new OrderVo();
            orderVo.setOrderInfo(orders);
            orderVo.setAllSize(iPage.getPages());
            jsonResult.setCode(200);
            jsonResult.setData(orderVo);
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取用户未支付的订单信息")
    @GetMapping("/unpaid")
    public JsonResult queryUnpaid(Integer userId, Integer pageNum){
        JsonResult jsonResult = new JsonResult();
        Page page = new Page(pageNum, 4);
        IPage<OrderResult> iPage = orderService.queryPageUserId(page, userId, 1);
        List<OrderResult> orders = iPage.getRecords();
        for(int i = 0; i < orders.size(); i++){
            OrderResult o = orders.get(i);
            String infos = o.getGoodsDetailsId();
            o.setCreateTime(o.getCreateTime().plusMinutes(30));
            List<Integer> ids = StringUtils.changArr(infos);
            List<OrderGoodsVo> goodsInfo = orderInfoService.queryByIds(ids);
            o.setGoodsInfo(goodsInfo);
        }

        if(orders.size() == 0){
            jsonResult.setCode(200);
            jsonResult.setMessage("您还没有相关的订单");
        }else {
            OrderVo orderVo = new OrderVo();
            orderVo.setOrderInfo(orders);
            orderVo.setAllSize(iPage.getPages());
            jsonResult.setCode(200);
            jsonResult.setData(orderVo);
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取用户待发货订单信息")
    @GetMapping("/sending")
    public JsonResult querySending(Integer userId, Integer pageNum){
        JsonResult jsonResult = new JsonResult();
        Page page = new Page(pageNum, 4);
        IPage<OrderResult> iPage = orderService.queryPageUserId(page, userId, 2);
        List<OrderResult> orders = iPage.getRecords();
        for (int i = 0; i < orders.size(); i++) {
            OrderResult o = orders.get(i);
            String infos = o.getGoodsDetailsId();
            List<Integer> ids = StringUtils.changArr(infos);
            List<OrderGoodsVo> goodsInfo = orderInfoService.queryByIds(ids);
            o.setGoodsInfo(goodsInfo);
        }


        if(orders.size() == 0){
            jsonResult.setCode(200);
            jsonResult.setMessage("您还没有相关的订单");
        }else {
            OrderVo orderVo = new OrderVo();
            orderVo.setOrderInfo(orders);
            orderVo.setAllSize(iPage.getPages());
            jsonResult.setCode(200);
            jsonResult.setData(orderVo);
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取用户待收货订单信息")
    @GetMapping("/receiving")
    public JsonResult queryReceiving(Integer userId, Integer pageNum){
        JsonResult jsonResult = new JsonResult();
        Page page = new Page(pageNum, 4);
        IPage<OrderResult> iPage = orderService.queryPageUserId(page, userId,3);
        List<OrderResult> orders = iPage.getRecords();
        for (OrderResult o : orders) {
            String infos = o.getGoodsDetailsId();
            List<Integer> ids = StringUtils.changArr(infos);
            List<OrderGoodsVo> goodsInfo = orderInfoService.queryByIds(ids);
            o.setGoodsInfo(goodsInfo);
        }

        if(orders.size() == 0){
            jsonResult.setCode(200);
            jsonResult.setMessage("您还没有相关的订单");
        }else {
            OrderVo orderVo = new OrderVo();
            orderVo.setOrderInfo(orders);
            orderVo.setAllSize(iPage.getPages());
            jsonResult.setCode(200);
            jsonResult.setData(orderVo);
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取用户已完成的订单信息")
    @GetMapping("/arrived")
    public JsonResult queryArrived(Integer userId, Integer pageNum){
        JsonResult jsonResult = new JsonResult();
        LocalDateTime now  = LocalDateTime.now();
        Page page = new Page(pageNum, 4);
        IPage<OrderResult> iPage = orderService.queryPageUserId(page, userId, 4);
        List<OrderResult> orders = iPage.getRecords();
        for (OrderResult o : orders) {
            if(o.getEndTime() == null){
                continue;
            }else {
                String infos = o.getGoodsDetailsId();
                List<Integer> ids = StringUtils.changArr(infos);
                List<OrderGoodsVo> goodsInfo = orderInfoService.queryByIds(ids);
                o.setGoodsInfo(goodsInfo);
            }

        }

        if(orders.size() == 0){
            jsonResult.setCode(200);
            jsonResult.setMessage("您还没有相关的订单");
        }else {
            OrderVo orderVo = new OrderVo();
            orderVo.setOrderInfo(orders);
            orderVo.setAllSize(iPage.getPages());
            jsonResult.setCode(200);
            jsonResult.setData(orderVo);
        }
        return jsonResult;
    }

    @GetMapping("/query/expressInfo")
    @ApiOperation(value = "查询用户订单的快递信息")
    public JsonResult queryExpressInfo(Integer userId,String no){
        JsonResult jsonResult = new JsonResult();
        String phone = null;
        String num = null;
        String arr = null;
        List<Order> orders = orderService.queryOfUserId(userId, no);
        // 对订单信息去重
        List<Order> newList = orders.stream()
                .filter(ListUtils.distinctByKey(Order::getNo))
                .collect(Collectors.toList());
        newList.forEach(System.out::println);
        for (Order o : newList){
            phone = addressService.getOneById(o.getAddressId()).getPhone();
            arr = expressService.getById(o.getExpressId()).getAbbr();
            num = expressService.getById(o.getExpressId()).getNumber();
        }

        HttpResult expressInfo = ExpressInfoUtil.getExpressInfo(arr,phone, num);
        if(expressInfo != null){
            jsonResult.setCode(expressInfo.getStatus());
            jsonResult.setData(expressInfo.getBody());
        }
        return jsonResult;
    }

    @DeleteMapping("/del")
    @ApiOperation(value = "删除订单")
    public JsonResult cancellationOrder(String no, Integer userId){
        JsonResult jsonResult = new JsonResult();

        boolean res = false;

        OrderInfo condition = new OrderInfo();
        // 根据订单编号查询
        List<Order> orders = orderService.queryOfUserId(userId, no);

        for (Order o : orders){

            if(o.getState() == 3 || o.getState() == 2 || o.getState() == 1){
                throw new BusinessException(ResponseEnum.STATE_INVALID_ERROR);
            }

            // 组装删除对象
            condition.setUserId(o.getUserId());
            condition.setId(o.getSellInfoId());
            res = orderInfoService.removeById(condition);
            res = orderService.removeById(o);
        }
        if (res){
            jsonResult.setCode(200);
            jsonResult.setMessage("删除成功！");
        }else {
            jsonResult.setMessage("删除失败！");
        }
        return jsonResult;
    }

    @GetMapping("/query/name")
    @ApiOperation(value = "根据条件搜索订单")
    public JsonResult cancellationOrder(Integer userId, String condition){
        JsonResult jsonResult = new JsonResult();
        int max = 23;
        String no = "";
        if(condition.length() != max){
            // 传的是名称
            condition = StringUtils.fuzzySuch(condition).trim();
        }else if(condition.length() == max){
            // 传的是订单编号
            no = condition;
        }
        List<OrderResult> orders = orderService.queryByUserId(userId, condition, no);
        System.out.println(orders);
        for(OrderResult o: orders){
            String infos = o.getGoodsDetailsId();
            List<Integer> ids = StringUtils.changArr(infos);
            List<OrderGoodsVo> goodsInfo = orderInfoService.queryByIds(ids);
            o.setGoodsInfo(goodsInfo);
        }

        if(orders.size() == 0){
            jsonResult.setCode(200);
            jsonResult.setMessage("很遗憾！没有找到符号条件的信息");
        }else {
            jsonResult.setCode(200);
            jsonResult.setData(orders);
        }

        return jsonResult;
    }

    @GetMapping("/query/count")
    @ApiOperation(value = "查询订单状态数量")
    public JsonResult queryCount(Integer userId){
        JsonResult jsonResult = new JsonResult();
        // 组装条件
        PageVo pageVo = new PageVo();
        Page page = new Page(1, 4);
        IPage<OrderResult> allIPage = orderService.queryPageUserId(page, userId, null);
        pageVo.setAllCount(allIPage.getTotal());
        IPage<OrderResult> unPayIPage = orderService.queryPageUserId(page, userId, 1);
        pageVo.setUnPayCount(unPayIPage.getTotal());
        IPage<OrderResult> sendingIPage = orderService.queryPageUserId(page, userId, 2);
        pageVo.setSendingCount(sendingIPage.getTotal());
        IPage<OrderResult> receivingIPage = orderService.queryPageUserId(page, userId, 3);
        pageVo.setReceivingCount(receivingIPage.getTotal());
        IPage<OrderResult> arrivedIPage = orderService.queryPageUserId(page, userId, 4);
        pageVo.setArrivedCount(arrivedIPage.getTotal());
        jsonResult.setCode(200);
        jsonResult.setData(pageVo);
        return jsonResult;
    }

    @PutMapping("update/address")
    @ApiOperation(value = "修改订单地址")
    public JsonResult updateOrderByNo(String no, Integer userId, Integer addressId){
        JsonResult jsonResult = new JsonResult();
        AtomicBoolean res = new AtomicBoolean(false);
        List<Order> orders = orderService.queryOfUserId(userId, no);
        if(orders.size() > 0){
            orders.forEach( o -> {
                o.setAddressId(addressId);
                res.set(orderService.updateById(o));
            } );
        }
        if(res.get()){
            jsonResult.setCode(200);
            jsonResult.setMessage("修改成功！");
        }
        return jsonResult;
    }

    @PutMapping("/cancel")
    @ApiOperation(value = "取消订单")
    public JsonResult cancelOrderByNo(String no, Integer userId){
        JsonResult jsonResult = new JsonResult();
        AtomicBoolean res = new AtomicBoolean(false);
        List<Order> orders = orderService.queryOfUserId(userId, no);
        if(orders.size() > 0){
            orders.forEach( o -> {
                o.setState(5);
                o.setEndTime(LocalDateTime.now());
                res.set(orderService.updateById(o));
            } );
        }
        EmailUtils.SendSimpleEmail("多彩贵州取消订单通知", "当前订单号：" + orders.get(0).getNo().concat("用户已取消订单。"));
        if(res.get()){
            jsonResult.setCode(200);
            jsonResult.setMessage("取消成功！");
        }
        return jsonResult;
    }

    @PutMapping("/notarize")
    @ApiOperation(value = "确认收货")
    public JsonResult notarizeOrder(String no, Integer userId){
        JsonResult jsonResult = new JsonResult();
        AtomicBoolean res = new AtomicBoolean(false);
        List<Order> orders = orderService.queryOfUserId(userId, no);
        if(orders.size() > 0){
            orders.forEach( o -> {
                o.setState(4);
                o.setEndTime(LocalDateTime.now());
                res.set(orderService.updateById(o));
            } );
        }
        if(res.get()){
            jsonResult.setCode(200);
            jsonResult.setMessage("操作成功！");
        }
        return jsonResult;
    }

    @PostMapping("/again/buy")
    @ApiOperation(value = "再次购买")
    public JsonResult againBuy(String no, Integer userId){
        JsonResult jsonResult = new JsonResult();
        List<OrderInfoResult> orderInfos = orderService.queryByNo(userId, no);
        OrderInfoResult result = orderInfos.get(0);
        String[] goodsIds = result.getGoodsId().split(",");
        String[] counts = result.getCount().split(",");
        String[] prices = result.getSumPrice().split(",");
        boolean res = false;
        for (int i = 0; i < goodsIds.length; i++) {
            ShoppingCart target = new ShoppingCart();
            target.setUserId(userId);
            target.setGoodsId(Integer.parseInt(goodsIds[i]));
            target.setCount(Integer.parseInt(counts[i]));
            target.setSumPrice(new BigDecimal(prices[i]));
            ShoppingCart shoppingCart = shoppingCartService.queryOneByCondition(userId, target);
            if(shoppingCart == null){
               res = shoppingCartService.save(target);
            }else {
                shoppingCart.setCount(shoppingCart.getCount() + target.getCount());
                shoppingCart.setSumPrice(shoppingCart.getSumPrice().add(target.getSumPrice()));
                res = shoppingCartService.updateById(shoppingCart);
            }
        }

        if(res){
            jsonResult.setCode(200);
            jsonResult.setMessage("操作成功");
        }
        return jsonResult;
    }

    @PutMapping("/makeOut/state")
    @ApiOperation(value = "将用户已完成订单的开票状态改为true")
    public JsonResult test(String[] nos, Integer userId,Integer id){
        JsonResult jsonResult = new JsonResult();
        boolean res = false;
        for (int i = 0; i < nos.length; i++) {
            List<Order> orders = orderService.queryByCondition(userId, nos[i]);
            for (Order o : orders){
                o.setMakeOutState(true);
                o.setInvoiceId(id);
                res = orderService.updateById(o);
            }
        }
        if(res){
            jsonResult.setCode(200);
            jsonResult.setMessage("修改成功！");
        }else{
           jsonResult.setMessage("修改失败！");
        }
        return jsonResult;
    }

}

